package com.example.iorder.reservation;

import java.util.ArrayList;
import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;

import com.example.domain.OrderedMenuItem;
import com.example.iorder.R;
import com.example.iorder.SearchRestaurant;
import com.example.iorder.config.Config;
import com.example.iorder.util.DataStorage;
import com.example.iorder.util.HTTPClient;
import com.example.iorder.util.MessageManager;
import com.example.iorder.util.TextFormatter;

@SuppressWarnings("deprecation")
public class FinalOverview extends TabActivity {
	private TabHost tabHost;
	private ProgressDialog progress;
	ArrayList<ArrayList<OrderedMenuItem>> listOfMenuItems;
	int tableID = RESERVATION_ID_EMPTY;
	int restaurantID = RESERVATION_ID_EMPTY;
	boolean createReservationSuccessful = false;
	boolean createOrderedItemsSuccessful = false;
	final static int RESERVATION_ID_EMPTY = -1;
	String reservationErrorMessage;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reservation_final_overview);
		progress = new ProgressDialog(this);
		
		// Get the id of the reservation and restaurant
		Bundle reservationInfo = getIntent().getExtras();
		listOfMenuItems = (ArrayList<ArrayList<OrderedMenuItem>>) reservationInfo.getSerializable("menuItems");
		tableID = reservationInfo.getInt(getResources().getString(R.string.key_table_id));
		restaurantID = reservationInfo.getInt(getResources().getString(R.string.key_restaurant_id));
		
		tabHost = getTabHost();
		
		// Reservation date and time information
		Intent intentDateTime = new Intent().setClass(this, ViewDateAndTime.class);
		intentDateTime.putExtras(reservationInfo);
		addTab("DateAndTime", R.string.lbl_date_time, R.drawable.time, intentDateTime);
		
		// Restaurant information
		Intent intentGeneralInformation = new Intent().setClass(this, ViewRestaurantInfo.class);
		intentGeneralInformation.putExtras(reservationInfo);
		addTab("RestaurantDetails", R.string.lbl_restaurant_info, R.drawable.restaurant, intentGeneralInformation);
		
		// Reserved table information
		
		// Selected Menu Items
		Intent intentOrderedMenuItems = new Intent().setClass(this, ViewOrderedMenuItems.class);
		intentOrderedMenuItems.putExtras(reservationInfo);
		addTab("OrderedMenuItems", R.string.lbl_ordered_items, R.drawable.list, intentOrderedMenuItems);
		
		tabHost.setCurrentTab(0);
		
//		if (deleteOrderedMenuItemsInDB()) {
//			Toast.makeText(this, "Deleted everything!", Toast.LENGTH_SHORT).show();
//		} else {
//			Toast.makeText(this, "Deletion failed..", Toast.LENGTH_SHORT).show();
//		}
	}
	
	public void sendReservation(View view) {
		startLoadingIndicator();
		
		// Remember the position of the current tab
		int oldCurrentTab = tabHost.getCurrentTab();
		
		// Go to the activity of ordered items and retrieve the latest list of items to send to the server
		tabHost.setCurrentTab(2);
		ViewOrderedMenuItems viewOrderedItems = (ViewOrderedMenuItems) getCurrentActivity();
		listOfMenuItems = viewOrderedItems.getListOfMenuItems();
		
		// Go to the activity of date and time and retrieve the latest date and time
		tabHost.setCurrentTab(0);
		ViewDateAndTime viewDateAndTime = (ViewDateAndTime) getCurrentActivity();
		Calendar selectedDate = viewDateAndTime.getSelectedDate();
		final String selectedDateFormattedString = TextFormatter.formatDateToString(selectedDate);
		final String selectedTimeFormattedString = TextFormatter.formatTimeToString(selectedDate);
		reservationErrorMessage = "";
		
		// Set the current tab back to what it was
		tabHost.setCurrentTab(oldCurrentTab);
		
		Thread request = new Thread() {
			public void run() {
				Message msg = new Message();
        		String path = "";
        		HTTPClient httpClient = null;
        		String searchResult = "";
        		String postData = "";
        		JSONObject record = null;
        		
        		DataStorage dataStorage = DataStorage.getInstance(getApplicationContext());
				String userIdString = dataStorage.getStringElement("id");
        		
        		// First send request to add reservation
				// Get the user id, table id, date and time 
        		int userId = userIdString.length() > 0 ? Integer.parseInt(userIdString) : -1;
        		int tableId = tableID;
        		int restaurantId = restaurantID;
        		int reservationId = RESERVATION_ID_EMPTY;
        		try {
        			path = Config.URL_CREATE_RESERVATION;
        			httpClient = new HTTPClient(getBaseContext());
        			postData = ""
        					+ "{"
        					+ "\"userid\":" + userId + ","
        					+ "\"restaurantid\":" + restaurantId + ","
        					+ "\"tableid\":" + tableId + ","
        					+ "\"date\":\"" + selectedDateFormattedString + "\","
        					+ "\"time\":\"" + selectedTimeFormattedString + "\""
        					+ "}";
        			searchResult = httpClient.sendPOSTRequest(Config.IORDER_SERVER, path, postData);
        			
        			JSONObject jsonObject = new JSONObject(searchResult);
        			if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
    					// Connection to server was successful and data was received
    					if (jsonObject.get("status").toString().equals("200")) {
    						// Get the new reservation id
    						record = jsonObject.getJSONObject("data");
    						
							try {
								String rIdString = record.optString("ID");
								reservationId = Integer.parseInt(rIdString);
							} catch (Exception e) {
								Log.e("Parsing created reservation", e.getMessage());
							}
    						
    						createReservationSuccessful = true;
    					} else {
    						reservationErrorMessage = jsonObject.get("msg").toString();
    					}
        			}
        		} catch (Exception e) {
        			Log.e("Error while sending reservation", e.getMessage());
        		}
				
				// Lastly, send request to add ordered menu items
        		int amountAddedExpected = 0;
        		int amountAdded = 0;
        		if (reservationId != RESERVATION_ID_EMPTY) {
	        		try {
	        			path = Config.URL_ORDERED_MENU_ITEMS;
	        			httpClient = new HTTPClient(getBaseContext());
	        			for (ArrayList<OrderedMenuItem> menuItemList : listOfMenuItems) {
	        				for (OrderedMenuItem orderedItem : menuItemList) {
	        					if (orderedItem.getCurrentAmount() > 0) {
	        						amountAddedExpected++;
		        					int itemId = orderedItem.getId();
				        			postData = ""
				        					+ "{"
				        					+ "\"MenuItemID\":" + itemId + ","
				        					+ "\"ReservationID\":" + reservationId + ","
				        					+ "\"Amount\":" + orderedItem.getCurrentAmount()
				        					+ "}";
				        			searchResult = httpClient.sendPOSTRequest(Config.IORDER_SERVER, path, postData);
				        			
				        			JSONObject jsonObject = new JSONObject(searchResult);
				    				if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
				    					// Connection to server was successful and data was received
				    					if (jsonObject.get("status").toString().equals("200")) {
				    						amountAdded++;
				    					}
				    				}
	        					}
	        				}
	        			}
	        			
	        			if (amountAddedExpected == amountAdded) {
	        				// Every ordered item added successfully
	        				createOrderedItemsSuccessful = true;
	        			}
	        		} catch (Exception e) {
	        			msg.getData().putString("exception", e.toString());
	        		}
        		}
        		
        		
        		
			}
		};
		request.start();
		try {
			request.join();
		} catch (InterruptedException e) {
			Log.e("Waiting for reservation request", e.getMessage());
		}
		
		// Show confirmation message when everything was successful
		LayoutInflater inflater = getLayoutInflater();
		View layout = null;
		if (createReservationSuccessful && createOrderedItemsSuccessful) {
			Toast messageView = new Toast(getApplicationContext());
			
			Drawable image = getResources().getDrawable(R.drawable.checkmark_green_2);
			String message = "Reservering is verzonden.";
			layout = MessageManager.getMessageView(inflater, image, message);
			
			messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			messageView.setDuration(Toast.LENGTH_LONG);
			messageView.setView(layout);
			messageView.show();
			
			Intent intent = new Intent(FinalOverview.this, SearchRestaurant.class);
			startActivity(intent);
			finish();
			
		} else {
			Toast messageView = new Toast(getApplicationContext());
			
			Drawable image = getResources().getDrawable(R.drawable.error_2);
			String message = "Er ging iets mis. Probeer later opnieuw.";
			if (reservationErrorMessage.length() > 0)
				message += "\n" + reservationErrorMessage;
			layout = MessageManager.getMessageView(inflater, image, message);
			
			messageView.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			messageView.setDuration(Toast.LENGTH_LONG);
			messageView.setView(layout);
			messageView.show();
			
			if (!createReservationSuccessful)
				Log.e("Create reservation", "Creating reservation was unsuccessful");
			if (!createOrderedItemsSuccessful)
				Log.e("Create reservation", "Creating ordered items was unsuccessful");
			
			finish();
		}
		
		stopLoadingIndicator();
	}
	
	private void addTab(String tag, int titleResourceID, int drawableResourceID, Intent layout) {
		TabSpec newTab = tabHost.newTabSpec(tag);
		newTab.setContent(layout);
		View view = prepareTabView(tabHost.getContext(), titleResourceID, drawableResourceID);
		newTab.setIndicator(view);
		tabHost.addTab(newTab);
	}
	
	private View prepareTabView(Context context, int titleResourceID, int drawableResourceID) {
		View view = LayoutInflater.from(context).inflate(R.layout.reservation_overview_tab, null);
		TextView tabLableView = (TextView) view.findViewById(R.id.tabLable);
		ImageView tabImageView = (ImageView) view.findViewById(R.id.tabImage);
		tabLableView.setText(getResources().getString(titleResourceID));
		tabImageView.setImageDrawable(getResources().getDrawable(drawableResourceID));
		return view;
	}
	
	private boolean deleteOrderedMenuItemsInDB() {
		boolean successfullyDeleted = false;
		HTTPClient httpClient = null;
		try {
			httpClient = new HTTPClient(getBaseContext());
			String searchResult = httpClient.sendDELETEAllOrderedMenuItemsRequest();
			try {
				JSONObject jsonObject = new JSONObject(searchResult);
				if (jsonObject.has("data") && jsonObject.has("msg")	&& jsonObject.has("status")) {
					if (jsonObject.get("status").toString().equals("200")) {
						successfullyDeleted = true;
					}
				}
			} catch (JSONException jsnE) {
				String errorMessage = "JSON Error: " + jsnE.getMessage();
				Toast.makeText(getBaseContext(), errorMessage,Toast.LENGTH_LONG).show();
			}

		} catch (Exception e) {
			stopLoadingIndicator();
			String errorMessage = getResources().getString(R.string.no_network_connection);
			Toast.makeText(getBaseContext(), errorMessage,Toast.LENGTH_LONG).show();
			Log.e("Loading menu", "Problem while loading menus and menu items: " + e.getMessage());
		}
		return successfullyDeleted;
	}
	
	private void startLoadingIndicator() {
		progress.setTitle(getResources().getString(R.string.loading_title));
        progress.setMessage(getResources().getString(R.string.sending_reservation));
        progress.show();
	}
	
	private void stopLoadingIndicator() {
		progress.dismiss();
	}
}
